﻿using COC.Debug;
using UnityEngine;
using System.Collections;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System;
using COC.Tool;
using COC.Exception;

namespace COC.Web
{
    /// <summary>
    /// in charge of resource summarizing update,or download new resource items into resource 'misc' folder.
    /// </summary>
		public class ResourceManager
		{

				private static ResourceManager instance;
				string resourceInfo;
				private WWW net;

				public static ResourceManager getInstance ()
				{
						if (instance == null) {
								instance = new ResourceManager ();
						}
						return  instance;
				}

				public IEnumerator DownloadBundlesInfos (string url)
				{
						if (url != null) {

								WWW www = new WWW (url);
								yield return www;

								if (www.error != null) {
										try {
												throw new System.Exception ("");
										} catch (CException ex) {

                                            DebugTool.Log("下载资源列表是发生错误:" + ex.Message);
										}
								} else {
										if (www.text != null && www.text.Length > 0) {
												resourceInfo = www.text;
										}
								}

						}
						yield return null;
						//testBundlesInfo (JSON);
		
				}

				public IEnumerator fetchZipResource (string url, string path)
				{




						yield return null;
				}
	
	
				/// <summary>
				/// 读取资源列表
				/// </summary>
				/// <returns>The bundles info.</returns>
				/// <param name="path">Path.</param>
				/// <param name="json">Json.</param>
				public IEnumerator SaveBundlesInfo (string url, string path, string json)
				{
						//pretty json 
						//json=JSONObject.Create(json).ToString(true);
						//判断文件是否是最新的
						//TODO
						///DownloadBundlesInfos (string url);
						/// 
						///

						//若不是则
						///访问网络
						//TODO
						//net=WWW(url);
                    DebugTool.Log("JSON=" + json);
						var parent = FileTools.CreateDirectorys ("WebService/Misc/AssetPackagesInfos", Application.dataPath);
                        DebugTool.Log("parent:=" + parent);
						string dir = parent.Substring (0, parent.Length);
						if (!Directory.Exists (path))
								Directory.CreateDirectory (path);
						string f = dir + "/" + path;
						if (!File.Exists (f)) {
								FileStream fs = File.Create (f);
								fs.Close ();
						}
						#if UNITY_WEBPLAYER
						#else
						DateTime t = new FileInfo (f).LastWriteTime;
						#endif
		
						byte[] bytes = System.Text.Encoding.UTF8.GetBytes (json);
						//判断是否与服务器一致
		
						//先保存原来文件 
						//更新资源文件
						//FileS
						//byte[] BUFFER = new byte[1024];
						FileStream fs2;
						try {
								fs2 = new FileStream (f, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
								fs2.Write (bytes, 0, bytes.Length);
						} catch (CException ex) {
								throw new CException (ex.Message);
								//fs2.Close();
						}
						fs2.Close ();
						yield return bytes;
				}


		}
}